const WebSocket = require('ws');

/**
 * 简单的717指令测试
 * 验证角色等级缓存是否正确
 */

class Simple717Tester {
  constructor() {
    this.ws = null;
    this.characterId = 2001; // 测试角色ID
  }

  async connect() {
    return new Promise((resolve, reject) => {
      console.log('🔌 连接WebSocket服务器...');
      
      this.ws = new WebSocket('ws://localhost:3001');
      
      this.ws.on('open', () => {
        console.log('✅ WebSocket连接成功');
        resolve();
      });
      
      this.ws.on('error', (error) => {
        console.error('❌ WebSocket连接失败:', error.message);
        reject(error);
      });
      
      this.ws.on('message', (data) => {
        try {
          const message = JSON.parse(data.toString());
          this.handleMessage(message);
        } catch (error) {
          console.error('❌ 解析消息失败:', error.message);
        }
      });
    });
  }

  handleMessage(message) {
    console.log('\n📨 收到消息:', JSON.stringify(message, null, 2));
    
    if (message.act_id === 717) {
      this.analyze717Response(message);
    } else if (message.act_id === 5) {
      console.log('✅ 角色选择成功');
    } else if (message.act_id === 1020) {
      console.log('✅ 1020查询成功');
    }
  }

  analyze717Response(message) {
    console.log('\n🔍 分析717本地玩家列表响应:');
    
    if (message.code === 0) {
      console.log('✅ 717查询成功');
      console.log(`📊 玩家数量: ${message.list ? message.list.length : 0}`);
      
      if (message.list && message.list.length > 0) {
        console.log('\n📋 本地玩家列表:');
        message.list.forEach((player, index) => {
          console.log(`\n玩家 ${index + 1}:`);
          console.log(`  - ID: ${player.id}`);
          console.log(`  - 名称: ${player.name}`);
          console.log(`  - 等级: ${player.lvl}`);
          console.log(`  - 性别: ${player.sex}`);
          console.log(`  - 职业: ${player.type}`);
          
          // 检查等级信息
          if (player.id === this.characterId) {
            console.log(`  🎯 这是当前测试角色，等级: ${player.lvl}`);
            if (player.lvl === 1) {
              console.log(`  ⚠️  警告：等级仍然是1级，可能缓存未更新`);
            } else {
              console.log(`  ✅ 等级信息正确：${player.lvl}级`);
            }
          }
        });
        
      } else {
        console.log('📭 当前区域没有其他玩家');
      }
      
    } else {
      console.log('❌ 717查询失败');
      console.log(`错误信息: ${message.message || '未知错误'}`);
    }
  }

  async testSequence() {
    try {
      await this.connect();
      
      // 等待连接稳定
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      console.log('\n🧪 开始测试序列...');
      
      // 1. 选择角色
      console.log('\n步骤1: 选择角色');
      const roleRequest = {
        c: 5,
        d: { roleId: this.characterId }
      };
      this.ws.send(JSON.stringify(roleRequest));
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 2. 查询玩家信息（1020）
      console.log('\n步骤2: 查询玩家信息（1020）');
      const infoRequest = {
        c: 1020,
        d: { userId: this.characterId }
      };
      this.ws.send(JSON.stringify(infoRequest));
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 3. 查询本地玩家列表（717）
      console.log('\n步骤3: 查询本地玩家列表（717）');
      const listRequest = {
        c: 717,
        d: { pageNum: 0 }
      };
      this.ws.send(JSON.stringify(listRequest));
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      console.log('\n🎉 测试序列完成');
      
    } catch (error) {
      console.error('❌ 测试执行失败:', error.message);
    } finally {
      if (this.ws) {
        this.ws.close();
        console.log('🔌 WebSocket连接已关闭');
      }
    }
  }
}

// 执行测试
if (require.main === module) {
  const tester = new Simple717Tester();
  tester.testSequence()
    .then(() => {
      console.log('\n✅ 717简单测试完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('\n❌ 717简单测试失败:', error.message);
      process.exit(1);
    });
}

module.exports = { Simple717Tester };
